﻿#define _CRT_SECURE_NO_WARNINGS
#include"SQList.h"

void SLInit(SL* ps)
{
	ps->arr = NULL;
	ps->size = ps->capcity = 0;
}

void CheckCapcity(SL* ps)
{
	if (ps->capcity == ps->size)
	{
		int newCapcity = ps->capcity == 0 ? 4 : ps->capcity * 2;
		SqDataType* tmp = (SqDataType*)realloc(ps->arr, newCapcity * sizeof(SqDataType));
		if (tmp == NULL)
		{
			perror("realloc");
			exit(1);
		}
		ps->arr = tmp;
		ps->capcity = newCapcity;
	}
}

//尾插
void SLPushBack(SL* ps, SqDataType x)
{
	assert(ps);

	//尾插空间不够要扩容
	CheckCapcity(ps);
	
	ps->arr[ps->size++] = x;
}

//头插
void SLPushFront(SL* ps, SqDataType x)
{
	assert(ps);
	CheckCapcity(ps);
	for (int i = ps->size; i>0; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[0] = x;
	++ps->size;
}

void SLPrint(SL* ps)
{
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ",ps->arr[i]);
	}
	printf("\n");
}

//尾删
void SLPopBack(SL* ps)
{
	assert(ps && ps->size);
	--ps->size;
}

//头删
void SLPopFront(SL* ps)
{
	assert(ps && ps->size);
	for (int i = 0; i < ps->size - 1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}

//查找数据
int SLFind(SL* ps, SqDataType x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->arr[i] == x)
		{
			return 1;
		}
	}
	return -1;
}

//指定位置之前插⼊数据
void SLInsert(SL* ps, int pos, SqDataType x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	CheckCapcity(ps);
	for (int i = ps->size; i > pos; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[pos] = x;
	++ps->size;
}

//删除指定位置的数据
void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	for (int i = pos; i < ps->size; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	--ps->size;
}

//销毁
void SLDesTroy(SL* ps)
{
	assert(ps);
	if (ps->arr)
	{
		free(ps->arr);
		ps->arr = NULL;
	}
	ps->capcity = ps->size = 0;
}